//
//  UIView+Extension.swift
//  SwiftProject
//
//  Created by qindong on 2021/6/17.
//

import Foundation

extension UIView {
    enum ShakeDirection : Int {
        case horizontal = 0
        case vertical
    }

    func shakeWith(_ time : Int = 10, _ speed : TimeInterval = 0.1, _ range : CGFloat = 5, _ shakeDirection : ShakeDirection = .horizontal, _ currentTimes : Int = 0, _ direction : CGFloat = 1) {
        UIView.animate(withDuration: speed) {
            self.transform = shakeDirection == .horizontal ? CGAffineTransform(translationX: range * direction, y: 0) : CGAffineTransform(translationX: 0, y: range * direction)
        } completion: { finished in
            if currentTimes >= time {
                UIView.animate(withDuration: speed) {
                    self.transform = CGAffineTransform.identity
                }
                return
            }
            self.shakeWith(time - 1, speed, range, shakeDirection, currentTimes + 1, direction * -1)
        }
    }
}
